<?php

namespace app\controller\wmapi\partner;

use app\controller\wmapi\IndexController;
use app\model\WaChannel;
use app\model\WaSupplier;
use app\model\WaSupplierInsuranceCompanyRelevance;
use Illuminate\Support\Facades;
use Illuminate\Support\Facades\Validator;
use plugin\admin\app\common\Util;
use plugin\admin\app\model\Admin;
use support\Request;
use app\model\WaAdmins;
use app\model\WaRoles;
use app\model\WaMembers;
use app\model\WaRules;
use app\model\WaDepartment;
use app\model\WaAdminRoles;
use Illuminate\Support\Facades\DB;
use Tymon\JWTAuth\Facades\JWTAuth;
use Illuminate\Support\Facades\Cache;
use Tinywan\Validate\Validate;
use Intervention\Image\ImageManagerStatic as Image;
use app\model\WaSupplierInsuranceCompany;

class WaSupplierInsuranceCompanyController extends Validate
{
    /**
     * 保险公司供应商管理 -列表-分页
     * @param Request $request
     * @return mixed
     */
    public function insuranceCompanyList(Request $request)
    {
        $param = $request->all();
        $fields = ['*'];
        $condition = [];
        $between = [];


        if ($param['name']) {
            $condition [] = ['name', 'like', '%' . $param['name'] . '%'];
        }

        if ($param['phone']) {
            $condition [] = ['phone', 'like', '%' . $param['phone'] . '%'];
        }


        if ($param['start_time'] && $param['end_time']) {
            $between [] = [$param['start_time'], $param['end_time']];
        }

        $condition [] = ['status', '!=', 4];


        $page = page($param['page']);
        $pageNum = pageNum($param['pageNum']);
        $rule = WaSupplierInsuranceCompany::list($page, $pageNum, $fields, $condition, $between);

        return IndexController::successed($rule, '保险公司供应商列表');
    }

    /**
     * 保险公司供应商管理 -列表-不分页
     * @param Request $request
     * @return mixed
     */
    public function insuranceCompanyAll(Request $request)
    {
//        process($request);
        $param = $request->all();
        $fields = ['*'];
        $condition = [];
        if ($param['supplier_name']) {
            $condition [] = ['name', 'like', '%' . $param['supplier_name'] . '%']; // 保险公司供应商名称
        }

        $condition [] = ['status', '!=', 4];


        $rule = WaSupplierInsuranceCompany::all($fields, $condition);
        return IndexController::successed($rule, '保险公司供应商列表');
    }


    /**
     * 保险公司供应商-创建
     * @param Request $request
     * @return \support\Response
     */
    public function insuranceCompanyCreate(Request $request)
    {
//        process($request);
        $param = $request->all();
        $adminId = json_decode(adminId($request));

        /**
         * 验证规则
         */
        $data = [
            'name' => $param['name'], // 上牌供应商名字
            'credit_code' => $param['credit_code'],// 组织机构信用代码
            'linkman' => $param['linkman'], // 联系人
            'phone' => $param['phone'],
            'email' => $param['email'],
            'legal_person_name' => $param['legal_person_name'], // 法人姓名
            'legal_person_phone' => $param['legal_person_phone'], // 法人手机
            'legal_person_identity_card' => $param['legal_person_identity_card'], // 法人身份证号码
            'address' => $param['address'],
            'remark' => $param['remark'], // 备注
            'registered_address' => $param['registered_address'], // 注册地址
            'business_scope' => $param['business_scope'], // 经营范围
            'created_at' => dateTime(),
            'admin_id' => $adminId->id, // 创建人
            'status' => 0,

            'legal_person_identity_left' => $param['legal_person_identity_left'], // 法人身份证正面
            'door_imgs' => json_encode($param['door_imgs']), // 门店照片 多张 数组格式
            'legal_person_identity_right' => $param['legal_person_identity_right'], // 法人身份证反面
            'business_license_img' => $param['business_license_img'], // 营业执照号照片

            'province' => $param['province'],
            'city' => $param['city'],
//            'firmname' => $param['firmname'], // 企业名称
//            'subbranch_name' => $param['subbranch_name'],

        ];
        if ($param['account_information']){
            $data['account_information'] =   json_encode($param['account_information']); // 账户信息
        }

//        $data['compulsory_insurance_fee'] = $param['compulsory_insurance_fee']; // 交强险
//        $data['commercial_insurance_fee'] = $param['commercial_insurance_fee']; // 商业险

//        $validate = self::validateAdd($data);
//        if (!$validate) {
//            return IndexController::errored('', '保险公司供应商入参有误');
//        }
        $where = [];
//        $where [] = ['phone' ,'=', $param['phone']];
//        $where [] = ['status' ,'!=', 4];
        $whereOr = [];
        $whereOr [] = ['name' ,'=', $param['name']];
        $whereOr [] = ['status' ,'!=', 4];
        $find = WaSupplierInsuranceCompany::findOr($where,$whereOr);
        $find = json_decode($find);
        if ($find) {
            if (property_exists($find, 'id')) {
                return IndexController::errored('', '保险公司供应商创建失败,保险公司供应商名称、类型、地区已存在');
            }
        }
        \support\Db::beginTransaction();
        try {
            $res = WaSupplierInsuranceCompany::created($data);
            if (!$res) {
                return IndexController::errored($res, '保险公司供应商创建失败');
            }
            \support\Db::commit();
            echo $res;
            return IndexController::successed($res, '保险公司供应商创建成功');
        } catch (\Throwable $exception) {
            IndexController::logError('insuranceCompanyCreate', $param, $adminId, $exception);
            \support\Db::rollBack();
            return IndexController::errored($exception, '保险公司供应商创建失败');
        }


    }

    public static function validateAdd($data)
    {
        $rule = [
            'name' => 'require', // 上牌供应商名字
            'address' => '',
            'phone' => 'require',
            'email' => 'require',
            'credit_code' => 'require',// 组织机构信用代码
            'linkman' => 'require', // 联系人
            'legal_person_name' => 'require', // 法人姓名
            'legal_person_phone' => 'require', // 法人手机
            'legal_person_identity_card' => 'require', // 法人身份证号码
            'registered_address' => '', // 注册地址
            'business_license_img' => '', // 营业执照号照片
//            'billing_type' => 'require', // 1 增值税普通发票 2 增值税专用发票
            'payment_account_name' => 'require', // 开户名
            'payment_account' => 'require', // 银行账号
            'bank_name' => 'require', // 开户银行
//            'subbranch_name' => 'require', // 开户支行
            'business_scope' => '', // 经营范围
        ];


//        $validate = \Tinywan\Validate\Facade\Validate::rule($rule);
//
//        if (!$validate->check($data)) {
//            return $validate->getError();
//        }
        return true;
    }


    /**
     * 保险公司供应商-更新
     * @param Request $request
     * @return \support\Response
     */
    public function insuranceCompanyEdit(Request $request)
    {
//        process($request);
        $param = $request->all();
        $adminId = json_decode(adminId($request));
        /**
         * 验证规则
         */
        $data = [
            'name' => $param['name'], // 上牌供应商名字
            'credit_code' => $param['credit_code'],// 组织机构信用代码
            'linkman' => $param['linkman'], // 联系人
            'phone' => $param['phone'],
            'email' => $param['email'],
            'legal_person_name' => $param['legal_person_name'], // 法人姓名
            'legal_person_phone' => $param['legal_person_phone'], // 法人手机
            'legal_person_identity_card' => $param['legal_person_identity_card'], // 法人身份证号码
            'address' => $param['address'],
            'remark' => $param['remark'], // 备注
            'registered_address' => $param['registered_address'], // 注册地址
            'business_scope' => $param['business_scope'], // 经营范围

            'account_information' => json_encode($param['account_information']), // 账户信息

            'created_at' => dateTime(),
            'admin_id' => $adminId->id, // 创建人
            'status' => 0,

            'legal_person_identity_left' => $param['legal_person_identity_left'], // 法人身份证正面
            'door_imgs' => json_encode($param['door_imgs']), // 门店照片 多张 数组格式
            'legal_person_identity_right' => $param['legal_person_identity_right'], // 法人身份证反面
            'business_license_img' => $param['business_license_img'], // 营业执照号照片

            'province' => $param['province'],
            'city' => $param['city'],
//            'subbranch_name' => $param['subbranch_name'],

//            'firmname' => $param['firmname'], // 企业名称

        ];
        if ($param['account_information']){
            $data['account_information'] =   json_encode($param['account_information']); // 账户信息
        }

        $data['compulsory_insurance_fee'] = $param['compulsory_insurance_fee']; // 交强险
        $data['commercial_insurance_fee'] = $param['commercial_insurance_fee']; // 商业险

//        $validate = self::validateAdd($data);
//        if (!$validate) {
//            return IndexController::errored('', '保险公司供应商入参有误');
//        }

        $where = [];
//        $where [] = ['phone' ,'=', $param['phone']];
//        $where [] = ['status' ,'!=', 4];
        $whereOr = [];
        $whereOr [] = ['name' ,'=', $param['name']];
        $whereOr [] = ['status' ,'!=', 4];
        $find = WaSupplierInsuranceCompany::findOr($where,$whereOr);
        $find = json_decode($find);
        if ($find){
            if (property_exists($find, 'id')) {
                if ($param['insurance_id'] != $find->id) {
                    return IndexController::errored('', '保险公司供应商更新失败,保险公司供应商电话已存在');
                }
            }
        }

        $condition = [];
        $condition [] = ['id', '=', intval($param['insurance_id'])];
        \support\Db::beginTransaction();
        try {
            $res = WaSupplierInsuranceCompany::updated($condition, $data);

            \support\Db::commit();
            return IndexController::successed($res, '保险公司供应商更新成功');
        } catch (\Throwable $exception) {
            IndexController::logError('insuranceCompanyEdit', $param, $adminId, $exception);
            \support\Db::rollBack();
            return IndexController::errored($exception, '保险公司供应商更新失败');
        }

    }

    /**
     * 保险公司供应商-删除
     * @param Request $request
     * @return \support\Response
     */
    public function insuranceCompanyDel(Request $request)
    {
//        process($request);
        $param = $request->all();
        $condition = [];
        $condition [] = ['id', '=', $param['insurance_id']];
        $adminId = json_decode(adminId($request));
        $data = [
            'status' => 4,
            'updated_at' => dateTime(),
        ];
        \support\Db::beginTransaction();
        try {
            $res = WaSupplierInsuranceCompany::updated($condition, $data);
            if (!$res){
                return IndexController::errored('', '保险公司供应商-删除失败');
            }
//            $del = WaSupplierInsuranceCompany::deleted(['id' => $param['insurance_id']]);
            $relevance_del = WaSupplierInsuranceCompanyRelevance::delete(['parent_id' => $param['insurance_id']]);
            \support\Db::commit();
            return IndexController::successed('', '保险公司供应商-删除成功');
        } catch (\Throwable $exception) {
            IndexController::logError('insuranceCompanyDel', $param, $adminId, $exception);
            \support\Db::rollBack();
            return IndexController::errored($exception, '保险公司供应商-删除失败');
        }
    }

    /**
     * 保险公司供应商-详情
     * @param Request $request
     * @return \support\Response
     */
    public function insuranceCompanyDetail(Request $request)
    {
//        process($request);
        $param = $request->all();

        $condition = [];
        $condition [] = ['id', '=', intval($param['insurance_id'])];

        $rule = WaSupplierInsuranceCompany::find($condition);
        return IndexController::successed($rule, '保险公司供应商信息');
    }


}